<?php

namespace App\Http\Controllers;

//use Illuminate\Http\Request;
use Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Book;
use App\Models\UsersReg;
use App\Models\BooksComments;
use App\Models\BooksReviewComments;
use App\Models\Category as cat;
use App\Models\BookTempstorage;
use App\Models\BooksReview;
use App\Models\BooksPingfen;
use App\Models\PingfenInfo;
use Session;
use Redirect;

class BookController extends Controller
{

    public function index()
    {
        //每页显示15个记录
        $pre_page = 15;
        //$posts = Book::paginate($pre_page);

        //获得所有图书信息的数据->books数据库 按倒序
        $books = Book::orderBy('last_update', 'desc')->orderBy('book_id', 'desc')->paginate($pre_page);
        //书籍分类
        $fenleis = Cat::get();

        return view('books.layouts.bookslist', array(
            'books'   => $books,
            'fenleis' => $fenleis
            ));
    }

    public function bookscat($catid)
    {
        //分类里的书籍列表
        //每页显示15个记录
        $pre_page = 15;
        //$posts = Book::paginate($pre_page);

        //获得所有图书信息的数据->books数据库 按倒序
        $books = Book::where('cat_id', $catid)->orderBy('last_update', 'desc')->orderBy('book_id', 'desc')->paginate($pre_page);
        //获得相应分类名字
        $cats = cat::where('cat_id', $catid)->first();
        //书籍分类
        $fenleis = Cat::get();

        return view('books.layouts.bookscat', array(
            'books'   => $books,
            'cats'    => $cats,
            'fenleis' => $fenleis
            ));
    }

    public function store(Request $request)
    {
        //
    }

    public function show($id)
    {
        // 得到书籍的信息
        $books = Book::find($id);

        if($books == null) {
            //如果书籍信息没有，显示404页面
            abort(404);
        }

        $books->click_count =  $books->click_count + 1;
        $books->save();

        //显示短书评评论列表
        $bookscomments = BooksComments::where('book_id', $id)->orderBy('add_time', 'desc')->get();
        foreach($bookscomments as $comment)
        {
            //为了得到会员名字和头像
            $comment['users'] = $comment->hasOnUsersReg;
        }

        //显示长书评评论列表
        $booksreviews = BooksReview::where('book_id', $id)->orderBy('add_time', 'desc')->get();
        foreach ($booksreviews as $reviewuser) {
            //得到发布长评论的会员资料
            $reviewuser['users'] = $reviewuser->hasOnUsersReg;
        }

        //检查本书是否有用户评分过
        $bookid = $id;
        $uid = Session::get('nameid');
        //$ispingfen 不等于0，说明有评分
        $ispingfen = BooksPingfen::where('uid', $uid)->where('book_id', $bookid)->count();

        //评分的各种内容
        $bookspingfen = BooksPingfen::where('uid', $uid)->where('book_id', $bookid)->first();

        //评分信息
        $pingfeninfo = PingfenInfo::where('book_id', $bookid)->first();
        if(empty($pingfeninfo)) {
            $pf = 0;
        }
        else {
            $pf = 1;
        }

            return view('books.layouts.info', array(
                'books' => $books, 
                'bookscomments' => $bookscomments, 
                'booksreviews' => $booksreviews,
                'ispingfen' => $ispingfen,
                'bookspingfen' => $bookspingfen,
                'pingfeninfo'  => $pingfeninfo,
                'pf' => $pf
                ));
    }

    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        //
    }

    public function destroy($id)
    {
        //
    }

    public function addbookscomments()
    {
        //判断是否登录
        if(Session::has('name'))
        {
            $name = Session::get('name');
            $users = UsersReg::where('user_name', $name)->first();
            //$books = Book::find();

            $bookscomments = new BooksComments;

            $bookid = request::input('bookid');

            $bookscomments->book_id = $bookid;                   //评论的图书的bookid
            $bookscomments->uid = $users->uid;                   //评论的会员uid
            $bookscomments->message = request::input('message'); //发表的短评论内容
            $bookscomments->rating = request::input('rating');
            $bookscomments->add_time = time();                   //获取当前时间戳;

            $bookscomments->save();

            $users->shubi = $users->shubi + 1; //增加一书币
            $users->save(); //更新书币

            //return back()->withMessages(['XXXXXX']);
            //return back();
            return redirect('comment/'.$bookid);
        }
        else
        {
            return '请先登录后发表评论！';
        }
    }

    public function reviewcomments()
    {
        //发表的图书长评论的评论
        if(Session::has('name'))
        {
            $name = Session::get('name');
            $users = UsersReg::where('user_name', $name)->first();
            //$books = Book::find();

            $booksreviewcomments = new BooksReviewComments;

            $booksreviewcomments->uid = $users->uid;                   //评论的会员uid            
            $booksreviewcomments->review_id = request::input('reviewid');               //评论的id
            $booksreviewcomments->content = request::input('content'); //发表的短评论内容

            $booksreviewcomments->add_time = time();                   //获取当前时间戳;

            $booksreviewcomments->save();

            //return back()->withMessages(['XXXXXX']);
            //return back();
            //return redirect('review/'.$reviewid);
            return 'saveok';
        }
        else
        {
            //没有登录标识
            return 'no';
        }
    }

    public function addbooks()
    {
        //会员登录后添加图书
        return view('books.layouts.addbooks');
    }
    public function addinfo()
    {
        //添加图书信息
        $cats  = cat::all();
        $bookname = Request::input('bookname');
        $isbn = Request::input('isbn');
        return view('books.layouts.addinfo',array('bookname'=>$bookname, 'isbn'=>$isbn, 'cats'=>$cats));
    }
    public function saveinfo(Request $request)
    {
        //保存会员添加的书籍
        $booktempstorages = new BookTempstorage;

        //判断有没有上传文件
        if($request::hasFile('fengmian'))
        {

        //取得上传文件
        $file = $request::file('fengmian');
        //得到文件名
        //$clientName = $file -> getClientOriginalName();
       
        //得到上传文件的扩展名
        $entension = $file -> getClientOriginalExtension();
       
        //得到文件的类型 得到的结果是 image/jpeg
        //$mineType = $file -> getMimeType();
       
        // 缓存在tmp文件夹中的文件名 例如 phpD97C.tmp 这种类型的
        //$tmpName = $file ->getFileName();
       
        //这个表示的是缓存在tmp文件夹下的文件的绝对路径
        //例如 D:\wamp2.5\tmp\phpF26A.tmp
        //$realPath = $file -> getRealPath();
       
        //这里app_path()就是app文件夹所在的路径
        //$newName 可以是你通过某种算法获得的文件的名称
        //$path = $file -> move(app_path().'/uploads',$newName);

        //$dirName = 'uploads\yds1\\'; //windows 系统下目录结构
        $dirName = "uploads/books_temp/"; // linux 系统下的目录结构  ,保存临时的书籍封面
        $filename = time(); //用时间作为文件名字
        // $newName = 'yds' . $filename . '.' . $entension;
        // $path = $file -> move($dirName, $newName);
        //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符

        // $booktempstorages->bimg = $path;

        //获得图片文件的宽度，高度，文件类型 
            list($bigWidth, $bigHeight, $bigType) = getimagesize($file);
            /* 
            $bigType: 
            1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，
            7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，
            9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，
            15 = WBMP，16 = XBM 
            */        

            if($bigWidth > 300)
            {
                $width = 300;
                $height = $bigHeight * ($width  / $bigWidth);

                // 把文件读入一个字符串
                $imagedata = file_get_contents($file);
                // 创建缩略图画板
                $block = imagecreatetruecolor($width, $height);
                // 启用混色模式
                imagealphablending($block, false);
                // 保存PNG alpha通道信息
                imagesavealpha($block, true);
                // 创建原图画板
                $bigImg = imagecreatefromstring($imagedata);
                // 缩放
                imagecopyresampled($block, $bigImg, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHeight);

                // 小图片文件名字
                $newName = 'yds' . $filename . '.' . $entension;
                // 生成临时文件名,保存到$dirName目录下,此时文件数据为空
                $tmpFilename = tempnam($dirName, 'tmp');
                // 改变文件属性
                // chmod($tmpFilename, 0644);
                // 保存图片,写数据到临时文件里
                switch ($bigType) {
                    case 1: 
                        imagegif($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 2: 
                        // 保存临时文件，写数据到临时文件里
                        imagejpeg($block, $tmpFilename);
                        // 给临时文件$tmpFilename改名为$newName，并且保存到$dirName目录下
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 3: 
                        imagepng($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
                }
                // 销毁
                imagedestroy($block);

                //图片裁剪保存完毕end

                // 保存原始图片
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path_m = $file -> move($dirName, $newName_m);
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符

            }
            else {
                // 图片宽度<=300
                $newName = 'yds' . $filename . '.' . $entension;
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path = $file -> move($dirName, $newName);
                $path_m = copy($path, $dirName . $newName_m);
                $path_m = $dirName . $newName_m;
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符
            }        

            $booktempstorages->bimg = $path;
            $booktempstorages->bimg_m = $path_m;

        }

        //获得用户的uid
        //$name = Session::get('name');
        $uid = Session::get('nameid'); 
        
        $booktempstorages->book_name = trim(request::input('bookname'));
        $booktempstorages->uid= $uid; // 上传用户的uid
        $booktempstorages->yuanzuoming = trim(request::input('yuanzuoming'));
        $booktempstorages->fubiaoti = trim(request::input('fubiaoti'));
        $booktempstorages->zuozhe = trim(request::input('zuozhe'));
        $booktempstorages->yizhe = trim(request::input('yizhe'));
        $booktempstorages->chubanshe = trim(request::input('chubanshe'));
        $booktempstorages->chubannian = trim(request::input('chubannian'));
        $booktempstorages->yeshu = trim(request::input('yeshu'));
        if(request::input('zhuangzhen')!='') {
            $booktempstorages->zhuangzhen = request::input('zhuangzhen');
        }
        else {
            $booktempstorages->zhuangzhen = trim(request::input('zzqita'));
        }
        $booktempstorages->dingjia = trim(request::input('dingjia'));
        $booktempstorages->isbn = trim(request::input('isbn'));
        $booktempstorages->congshu = trim(request::input('congshu'));
        $booktempstorages->neirongjianjie = request::input('neirongjianjie');
        $booktempstorages->zuozhejianjie = request::input('zuozhejianjie');
        $booktempstorages->mulu = request::input('mulu');
        $booktempstorages->cat_id = request::input('catname');
        $booktempstorages->add_time = time(); //获取当前时间戳

        $booktempstorages->save();
        
        $bookid = $booktempstorages->book_id;
        return Redirect::to('saveok/'. $bookid);
    }
    public function showinfo($id)
    {
        //发布书籍完成后的显示
        $booktempstorages = BookTempstorage::find($id);
        if($booktempstorages == null)
        {
            abort(404);
        }
        return view('books.layouts.saveok', array('booktempstorages' => $booktempstorages)); 
    }
    public function checkisbn()
    {
        //ajax 检测书籍的isbn是否重复
        $isbn = request::input('isbn');
        if(Book::where('isbn', $isbn)->exists()){
            return 'ok';
        } 
    }
    public function bookreview($id) {
        //发布长书评
        $books = Book::find($id);
        return view('books.layouts.newbookreview', array('books' => $books));
    }
    public function savebookreview() {
        //保存长书评
        $booksreviews = new BooksReview;
        $booksreviews->book_id = request::input('bookid');

        //获得用户的uid
        //$name = Session::get('name');
        $uid = Session::get('nameid');
        $booksreviews->uid = $uid; // 保存书评用户的uid

        $booksreviews->title = trim(request::input('title'));
        $booksreviews->rating = request::input('rating');
        $booksreviews->bookreview = request::input('bookreview');
        $booksreviews->add_time = time(); //获取当前时间戳

        $booksreviews->save();
        
        $id = $booksreviews->id;
        return Redirect::to('review/'. $id);
    }

    public function reviewshow($id)
    {
        //显示发布的长书评
        $booksreviews = BooksReview::find($id);
        $books = Book::where('book_id', $booksreviews->book_id)->first();
        $users = UsersReg::where('uid', $booksreviews->uid)->first();
        $booksreviewcomments = BooksReviewComments::where('review_id', $id)->orderBy('add_time', 'desc')->get();
        foreach ($booksreviewcomments as $booksreviewcomment) {
            //得到发布长评论的会员资料
            $booksreviewcomment['users'] = $booksreviewcomment->hasOnUsersReg;
        }
        if(Session::has('name'))
        {
            $name = Session::get('name');
            $uname = UsersReg::where('user_name', $name)->first();
            return view('books.layouts.review', array(
                'booksreviews' => $booksreviews, 
                'books' => $books, 
                'users' => $users,                
                'uname' => $uname, //登录用户的数据
                'booksreviewcomments' => $booksreviewcomments
                ));
        }else{ 
            return view('books.layouts.review', array(
                'booksreviews' => $booksreviews, 
                'books' => $books, 
                'users' => $users,
                'booksreviewcomments' => $booksreviewcomments
                ));
        }
    }

    public function reviewslist($bookid)
    {
        //显示长书评评论列表
        $booksreviews = BooksReview::where('book_id', $bookid)->orderBy('add_time', 'desc')->get();
        foreach ($booksreviews as $reviewuser) {
            //得到发布长评论的会员资料
            $reviewuser['users'] = $reviewuser->hasOnUsersReg;
        }
        $books = Book::where('book_id', $bookid)->first();
        return view('books.layouts.reviewslist', array('booksreviews' => $booksreviews, 'books' => $books));
    }

    public function commentlist($bookid)
    {
        //显示发布的短书评
        $bookscomments = BooksComments::where('book_id', $bookid)->orderBy('add_time', 'desc')->get();
        $books = Book::where('book_id', $bookid)->first();
        foreach($bookscomments as $comment)
        {
            //为了得到会员名字和头像
            $comment['users'] = $comment->hasOnUsersReg;
        }
        if(Session::has('name'))
        {
            $name = Session::get('name');
            $users = UsersReg::where('user_name', $name)->first(); 
            return view('books.layouts.comment', array(
                'bookscomments' => $bookscomments, 
                'books' => $books,                
                'users' => $users
                ));
        }
        else {
            return view('books.layouts.comment', array(
                'bookscomments' => $bookscomments, 
                'books' => $books
                ));
        }
    }

    
}
